import 'dart:async';
import 'package:dio/dio.dart';
import 'package:flutter_elm/json/response_item.dart';
import 'package:flutter_elm/json/user_item.dart';

//code 2开头都是请求成功的，只不过业务上可能不成功
//code 4开头都是请求不成功的。（一般都是 客户端-前端代码问题）
class UserApi {
  late Dio _dio;
  String baseUrl = "http://192.168.1.12:8080/UserController";
  String contents = "";

  UserApi() {
    _dio = Dio();
    // 设置contentType
    // _dio.options.headers['Content-Type'] = 'application/x-www-form-unlencoded';
  }

  //注意，在界面调用接口前， 都先检测一下apikey的值。
  Future<ResponseItem<UserItem?>> userRegister(String id, String pw, String name, int sex) async {
    var url =  baseUrl+"/addUser";
    //发送formdata 或者 x-www-form-urlencoded 格式的数据 需要用FormData封装
    FormData userJson = FormData.fromMap(
        {
          "id": id,
          "pw": pw,
          "name": name,
          "sex": sex,
        }
    );
    try {
      Response response = await _dio.post(
          url,
          data: userJson
      );
      // print("userRegister response.data:${response.data}");

      if(response.data.length==0){
        return ResponseItem(code: 201, data: null, message: "手机号重复，您已经注册过");
      }else{
        UserItem userItem = UserItem.fromJson(response.data);
        // 只能通过这样子获取response.data["userName"]，返回的json数据中的字段。
        // 不能response.data.userName，因为response.data系统默认是map类型的。
        // print("${response.data["userName"]}");
        return ResponseItem<UserItem>(code: 200, data: userItem, message: "注册成功");
      }
    } catch (e) {
      print('userRegister-Error: $e');
      return ResponseItem(code: 400, data: null, message: "客户端代码有问题");
    }
  }
  Future<ResponseItem<UserItem?>> userLogin(String id, String pw,) async {
    var url =  baseUrl+"/findByUserIdAndPassword";
    FormData userJson = FormData.fromMap({"id": id, "pw": pw,});
    try {
      Response response = await _dio.post(url, data: userJson);
      if(response.data.length==0){
        return ResponseItem(code: 201, data: null, message: "登录失败，手机号或密码错误");
      }else{
        UserItem userItem = UserItem.fromJson(response.data);
        return ResponseItem<UserItem>(code: 200, data: userItem, message: "登陆成功");
      }
    } catch (e) {
      print('userLogin-Error: $e');
      return ResponseItem(code: 400, data: null, message: "客户端代码有问题");
    }
  }
}

void main()async{
  UserApi userApi = UserApi();
  // var res = await userApi.userRegister("11111178912", "12345678912", "小李", 1);
  var res = await userApi.userLogin("12345678911", "1");
  print("${res.data?.userId}");
}